<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>myPromise</title>
</head>
<body>
    <script >

        var Padding = 'Padding'
        var Fulfilled = 'Fulfilled'
        var Rejected = 'Rejected'

        var MyPromise = function (fn) {
            // status 状态: Padding, Fulfilled, Rejected
            this._status = Padding;
            this.resolveFnList = [];
            this.rejectFnList = [];
            var self = this;

            var resolveFn = function(data) {
                let d = data
                for (var i = 0; i < self.resolveFnList.length; i++) {
                    var resolveFnItem = self.resolveFnList[i]
                    if (resolveFnItem instanceof  Function) {
                        try {
                            d = resolveFnItem(d)
                        } catch (error) {

                        }
                    }
                }
            }
            var rejectFn = function(err) {
                let d = err
                for (let resolveFnItem of self.rejectFnList) {
                    if (resolveFnItem instanceof Function) {
                        d = resolveFnItem(d);
                    }
                }
            }

            fn = fn.bind(this)

            setTimeout(function() {
                fn(resolveFn, rejectFn)
            }, 0)
        }

        MyPromise.prototype.then = function (resolveFn, rejectFn) {
            this.resolveFnList.push(resolveFn)
            this.rejectFnList.push(rejectFn)
            return this
        }
        MyPromise.prototype.catch = function(rejectFn) {
            return this.then(undefined, rejectFn)
        }

        // ------------------------------------------------------------

        let p = new MyPromise(function (resolve, reject) {
            console.log('MyPromise instance')
            setTimeout(function () {
                resolve(10)
            }, 700)
        })
        p.then(function (resolveData) {
            console.log('resolveData ', resolveData)
            throw new Error('test myPromise error')
            return 20;
        })
        .then(function(d) {
            console.log(d);
            return 30;
        })
        .then(function(c) {
            console.log(c);
            return 40;
        })
        .catch(function(err) {
            console.log(err);
        })

    </script>
</body>
</html>